#include "service_server.h"
#include <iostream>

namespace cpp_backend {
namespace framework {

// ========================================
// ServiceRPCImpl 实现
// ========================================

grpc::Status ServiceRPCImpl::Call(
    grpc::ServerContext* context,
    const service_rpc::ServiceRequest* grpc_request,
    service_rpc::ServiceResponse* grpc_response
) {
    try {
        // 1. 转换gRPC请求 → framework::Request
        auto request = convert_from_grpc_request(grpc_request);
        
        // 2. 调用业务Service（复用现有代码）
        auto response = business_service_->HandleRequest(request);
        
        // 3. 转换framework::Response → gRPC响应
        convert_to_grpc_response(response, grpc_response);
        
        return grpc::Status::OK;
        
    } catch (const std::exception& e) {
        std::cerr << "[ServiceRPCImpl] Exception in Call: " << e.what() << std::endl;
        return grpc::Status(
            grpc::StatusCode::INTERNAL,
            e.what()
        );
    }
}

grpc::Status ServiceRPCImpl::HealthCheck(
    grpc::ServerContext* context,
    const service_rpc::HealthCheckRequest* request,
    service_rpc::HealthCheckResponse* response
) {
    try {
        response->set_healthy(business_service_->HealthCheck());
        response->set_service_name(business_service_->GetServiceName());
        response->set_version(business_service_->GetServiceVersion());
        response->set_uptime_seconds(get_uptime_seconds());
        
        return grpc::Status::OK;
        
    } catch (const std::exception& e) {
        std::cerr << "[ServiceRPCImpl] Exception in HealthCheck: " << e.what() << std::endl;
        return grpc::Status(
            grpc::StatusCode::INTERNAL,
            e.what()
        );
    }
}

Request ServiceRPCImpl::convert_from_grpc_request(
    const service_rpc::ServiceRequest* grpc_req
) {
    Request req;
    
    // 基本信息
    req.SetMethod(grpc_req->method());
    req.SetPath(grpc_req->path());
    
    // Headers
    for (const auto& [key, value] : grpc_req->headers()) {
        req.SetHeader(key, value);
    }
    
    // Params
    for (const auto& [key, value] : grpc_req->params()) {
        req.SetParam(key, value);
    }
    
    // Body（JSON反序列化）
    if (!grpc_req->body().empty()) {
        try {
            auto json_body = nlohmann::json::parse(grpc_req->body());
            req.SetBody(json_body);
        } catch (const std::exception& e) {
            std::cerr << "Failed to parse request body: " << e.what() << std::endl;
        }
    }
    
    // 认证信息
    int64_t user_id = grpc_req->user_id();
    req.SetUserId(user_id);
    req.SetUserName(grpc_req->username());
    req.SetUserRole(grpc_req->user_role());
    
    // 元信息
    req.SetClientIp(grpc_req->client_ip());
    req.SetRequestId(grpc_req->request_id());
    
    return req;
}

void ServiceRPCImpl::convert_to_grpc_response(
    const Response& resp,
    service_rpc::ServiceResponse* grpc_resp
) {
    // HTTP状态码
    grpc_resp->set_http_status(resp.GetHttpStatusCode());
    
    // 业务错误码
    grpc_resp->set_error_code(resp.GetErrorCodeValue());
    
    // 错误消息
    grpc_resp->set_message(resp.GetMessage());
    
    // Headers
    for (const auto& [key, value] : resp.GetHeaders()) {
        (*grpc_resp->mutable_headers())[key] = value;
    }
    
    // Body（JSON序列化）
    if (!resp.GetData().is_null()) {
        std::string body_str = resp.GetData().dump();
        grpc_resp->set_body(body_str);
    } else if (!resp.GetRawBody().empty()) {
        // 处理二进制响应体
        std::string body_str(resp.GetRawBody().begin(), resp.GetRawBody().end());
        grpc_resp->set_body(body_str);
    }
}

// ========================================
// ServiceServer 实现
// ========================================

void ServiceServer::register_service(IService* service) {
    if (!service) {
        throw std::invalid_argument("Service cannot be null");
    }
    
    service_impl_ = std::make_unique<ServiceRPCImpl>(service);
    
    std::cout << "[ServiceServer] Service registered: "
              << service->GetServiceName()
              << " v" << service->GetServiceVersion()
              << std::endl;
}

bool ServiceServer::start() {
    if (!service_impl_) {
        std::cerr << "[ServiceServer] No service registered" << std::endl;
        return false;
    }
    
    std::string server_address = "0.0.0.0:" + std::to_string(port_);
    
    grpc::ServerBuilder builder;
    
    // 添加监听端口
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    
    // 注册服务
    builder.RegisterService(service_impl_.get());
    
    // 构建并启动服务器
    grpc_server_ = builder.BuildAndStart();
    
    if (grpc_server_) {
        std::cout << "[ServiceServer] gRPC Server listening on "
                  << server_address << std::endl;
        return true;
    }
    
    std::cerr << "[ServiceServer] Failed to start gRPC server" << std::endl;
    return false;
}

void ServiceServer::wait_for_shutdown() {
    if (grpc_server_) {
        grpc_server_->Wait();
    }
}

void ServiceServer::stop() {
    if (grpc_server_) {
        std::cout << "[ServiceServer] Stopping gRPC server..." << std::endl;
        grpc_server_->Shutdown();
        grpc_server_.reset();
        std::cout << "[ServiceServer] gRPC server stopped" << std::endl;
    }
}

} // namespace framework
} // namespace cpp_backend
